const caches = require('../cache');
let cacheData = caches.get('history');
let MAX = 200;
try{
    cacheData = JSON.parse(cacheData);
    if(toString.call(cacheData) !== "[object Array]") throw new Error('type error')
}catch(e){
    cacheData = [];
}
function update(map){
    caches.set('history',JSON.stringify(map));
}

function getArrayIndex(id,list){
    for(let i=0,len = list.length;i<len;i++){
        if(id === list[i].id){
            return i;
        }
    }
    return -1;
}

export default {
    list:cacheData,
    check(id){
        return !!this.get(id);
    },
    get(id){
        let idx = getArrayIndex(id,this.list);
        return idx === -1 ? null : this.list[idx];
    },
    set(item){
        let id = item.id;
        let tmp = JSON.parse(JSON.stringify(item));
        if(tmp.content) delete tmp.content;
        tmp.history_time = +new Date;
        let idx = getArrayIndex(id,this.list);
        if(idx !== -1){
            this.list.splice(idx,1);
        }

        //最多保存40条历史记录
        if(this.list.length >= 40){
            this.list.pop();
        }
        this.list.unshift(tmp);
        update(this.list)
    },
    remove(id){
        let idx = getArrayIndex(id,this.list);
        if(idx !== -1){
            this.list.splice(idx,1);
            update(this.list)
        }
    }
}